<template>
  <div class="page">
    <div class="filter-card">
      <div class="header">
        <div class="title">用户管理</div>
        <div style="float:right;margin-right:10px;">
          <el-button size="mini" @click="showImportUserDialog">批量导入用户</el-button>
          <el-button size="mini" @click="showCreateDialog">新建用户</el-button>
        </div>
      </div>
      <div class="filter-form">
        <el-form inline size="mini"  style="display:flex;">
          <!-- <el-form-item label="姓名" class="baseFlex">
            <el-input placeholder="请输入用户姓名" v-model="filterForm.name" clearable></el-input>
          </el-form-item>-->
          <el-form-item label="员工号" class="baseFlex">
            <el-input
              placeholder="请输入员工号"
              v-model="filterForm.userId"
              clearable
              style="width:300px;"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="手机号"  class="baseFlex">
            <el-input placeholder="请输入手机号" v-model="filterForm.userPhone" clearable></el-input>
          </el-form-item>-->
          <el-form-item style="text-align: right;">
            <el-button type="primary" @click="setFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="table-card">
      <el-table align="center" :data="tableData.lists">
        <el-table-column label="员工号" prop="userId">
          <template slot-scope="scope">
            <text-alt :text="scope.row.userId"></text-alt>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="部门" prop="institution"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="状态" prop="isEfftctive"></el-table-column>
        <el-table-column
          label="最近操作时间"
          prop="operateTime"
          width="90px"
          :formatter="tableFormatDate"
        ></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" plain @click="showAssignDialog(scope.row)">分配</el-button>
            <el-button type="primary" size="mini" plain @click.native="deleteUser(scope.row)">删除</el-button>
            <el-button
              size="mini"
              plain
              v-if="!isEffectiveActive(scope.row.efftctiveSymbol)"
              @click="activeRole(scope.row)"
            >启用</el-button>
            <el-button
              size="mini"
              plain
              v-if="isEffectiveActive(scope.row.efftctiveSymbol)"
              @click="showRoleDialog(scope.row)"
            >关闭</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex-row flex-justify-between flex-align-center table-pagination">
        <div style="font-size: 12px">共{{tableData.total}}条</div>
        <el-pagination
          style="margin-left: -10px"
          background
          @current-change="fetchWithPagination"
          :current-page.sync="tableData.pageNumber"
          :page-size="tableData.pageSize"
          @size-change="fetchWithPageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          layout="prev, pager, next,jumper"
          :total="tableData.total"
        ></el-pagination>
      </div>
    </div>

    <!--    -->
    <el-dialog :visible.sync="createDialog" title="新建用户">
      <el-form label-width="80px" ref="newUserForm" :model="newUserForm" :rules="rules">
        <el-form-item label="员工号" prop="userId">
          <el-input v-model="newUserForm.userId" placeholder="请输入员工号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="newUserForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="机构号" prop="institution">
          <el-input v-model="newUserForm.institution" placeholder="请输入机构号"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="newUserForm.userPhone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUserForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="newUserForm.roleId" filterable placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.roleId"
              :value="role.roleId"
              :label="role.roleName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" size="small" @click="confirmCreate">确认</el-button>
        <el-button @click="cancelCreate" size="small" style="margin-right: 20px;">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog class="role-dialog" :visible.sync="roleDialog" width="350px">
      <div class="role-container flex-column flex-align-center flex-justify-around">
        <img src="@/assets/images/user_cancel.png" alt />
        <span>是否关闭改用户权限</span>
        <div>
          <el-button type="primary" @click="confirmRole">确认</el-button>
          <el-button @click="cancelRole">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="assignDialog" width="350px">
      <div slot="title">分配角色</div>
      <div class="flex-column flex-align-center">
        <el-form label-width="80px" :model="assignForm" ref="assginRole" :rules="roleRules">
          <el-form-item label="角色名称" required prop="roleId">
            <el-select v-model="assignForm.roleId" filterable>
              <el-option
                v-for="role in roleList"
                :key="role.roleId"
                :value="role.roleId"
                :label="role.roleName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="confirmAssign">确认</el-button>
          <el-button @click="cancelAssign">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="uploadDialog" title="批量导入用户">
      <el-form label-width="100px">
        <el-form-item label="批量导入用户">
          <input
            :style="{display:uploadFile.name?'none':'inline'}"
            type="file"
            accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            @change="onUploadFileChanged"
            id="uploadFile"
          />
          <div v-if="uploadFile.name">
            {{uploadFile.name}}
            <el-button icon="el-icon-delete" type="text" size="mini" @click="onClearUploadFile"></el-button>
          </div>
        </el-form-item>
        <el-form-item label="模版下载">
          <a
            class="el-link el-link--primary"
            href="/static/批量导入用户模板.xlsx"
            download="批量导入用户模板.xlsx"
          >批量导入模板.xlsx</a>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="onConfirmUpload">确定</el-button>
        <el-button @click="onHideUploadDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TextAlt from "../../components/textAlt";
export default {
  name: "custom",
  components: { TextAlt },
  data() {
    return {
      baseUrl: "/api/user/list",
      filterForm: {
        name: "",
        userPhone: ""
      },
      tableData: {},
      createUmCode: "",
      createDialog: false,
      roleDialog: false,
      roleList: [],
      roleId: "",
      assignDialog: false,
      selectedRow: {},
      uploadDialog: false,
      uploadFile: {},
      assignForm: {
        roleId: ""
      },
      newUserForm: {
        userId: "",
        name: "",
        institution: "",
        userPhone: "",
        email: "",
        roleId: ""
      },
      roleRules: {
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }]
      },
      rules: {
        userId: [{ required: true, message: "请输入员工号", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        institution: [
          { required: true, message: "请输入机构号", trigger: "blur" }
        ],
        userPhone: [
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }]
      }
    };
  },
  mounted() {
    // this.fetchRoleList();
  },
  methods: {
    fetchRoleList() {
      const self = this;
      self.$get("/api/role/findAllRole").then(res => {
        self.roleList = res;
      });
    },
    showCreateDialog() {
      this.createDialog = true;
    },
    cancelCreate() {
      this.createDialog = false;
      this.createUmCode = "";
    },
    confirmCreate() {
      const self = this;
      self.$refs["newUserForm"].validate(valid => {
        if (valid) {
          self.$post("/api/user/add", self.newUserForm).then(res => {
            self.$message.success("添加成功");
            self.newUserForm = {
              userId: "",
              name: "",
              institution: "",
              userPhone: "",
              email: "",
              roleId: ""
            };
            self.setFilter();
            self.createDialog = false;
          });
        } else {
          return false;
        }
      });
    },
    toUserEdit(row) {
      this.$router.push({
        path: "/system/user/edit",
        query: { username: row.username }
      });
    },
    isEffectiveActive(value) {
      return Mapping.tools.valueEqMapping(Mapping.user.effective.active, value);
    },
    showAssignDialog(row) {
      this.selectedRow = row;
      this.assignDialog = true;
    },
    confirmAssign() {
      const self = this;
      self.$refs["assginRole"].validate(valid => {
        if (valid) {
          self
            .$post("/api/user/update", {
              userId: this.selectedRow.userId,
              username: this.selectedRow.username,
              roleId: this.assignForm.roleId
            })
            .then(res => {
              this.$message.success("操作成功");
              this.selectedRow = {};
              this.assignForm.roleId = "";
              this.assignDialog = false;
              self.setFilter();
            });
        } else {
          return false;
        }
      });
    },
    cancelAssign() {
      this.assignDialog = false;
      this.selectedRow = {};
    },
    showRoleDialog(row) {
      this.selectedRow = row;
      this.roleDialog = true;
    },
    confirmRole() {
      const self = this;
      self
        .$post("/api/user/update", {
          userId: this.selectedRow.userId,
          username: this.selectedRow.username,
          efftctiveSymbol: Mapping.user.effective.disabled.value
        })
        .then(res => {
          self.$message.success("操作成功");
          self.setFilter();
          self.selectedRow = {};
          self.roleDialog = false;
        });
    },
    cancelRole() {
      this.selectedRow = {};
      this.roleDialog = false;
    },
    activeRole(row) {
      const self = this;
      self
        .$post("/api/user/update", {
          userId: row.userId,
          username: row.username,
          efftctiveSymbol: Mapping.user.effective.active.value
        })
        .then(res => {
          self.$message.success("操作成功");
          self.setFilter();
        });
    },
    deleteUser(row) {
      const self = this;
      self
        .$confirm(`确认删除用户[${row.name}]?`, {
          cancelButtonClass: "cancelButtonClass",
          confirmButtonClass: "confirmButtonClass",
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
        .then(() => {
          self.$del(`/api/user/delete/${row.userId}`).then(res => {
            self.$message.success("操作成功");
            self.setFilter();
          });
        });
    },
    showImportUserDialog() {
      this.uploadDialog = true;
    },
    onHideUploadDialog() {
      this.onClearUploadFile();
      this.uploadDialog = false;
    },
    onConfirmUpload() {
      const self = this;
      if (!this.uploadFile.name) {
        this.$message.warning("请选择需上传的文件");
        return;
      }
      const formData = new FormData();
      formData.append("excelFile", this.uploadFile);
      self.$post("/api/user/upload", {}, formData).then(() => {
        self.$message.success("导入成功");
        self.onHideUploadDialog();
        self.setFilter();
      });
    },
    onUploadFileChanged(e) {
      this.uploadFile = e.target.files[0];
    },
    onClearUploadFile() {
      console.log(document.getElementById("uploadFile"));
      document.getElementById("uploadFile").value = "";
      this.uploadFile = {};
    }
  }
};
</script>

<style scoped lang="less">
.page {
  height: 100%;
  display: flex;
  flex-direction: column;

  .filter-card {
    padding: 0 10px;
    background: #fff;
  }

  .filter-card .header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f3f3f3;
    padding: 10px 0;
  }
  .el-message-box .cancelButtonClass {
    background: pink !important;
  }

  .filter-card .header .title {
    font-size: 14px;
  }

  .filter-form {
    padding: 10px 0;
  }

  .table-card {
    margin-top: 10px;
    background: #fff;
    padding: 10px;
    flex: 1;
    overflow-y: scroll;
  }

  .table-card .table-pagination {
    font-size: 14px;
  }

  .role-dialog {
    .role-container {
      height: 200px;

      img {
        width: 56px;
        height: 56px;
      }
    }
  }

  .el-link {
    font-size: 12px;
  }
}
</style>
